#!/usr/bin/env python

import sys, os, urllib2
import random

from BeautifulSoup import BeautifulSoup   

FREQUENCYPAGE="http://www.walottery.com/WinningNumbers/FrequencyOfNumbersDrawn/FrequencyOfNumbersDrawn.aspx?game=Hit5"
WINNINGNUMBERSPAGE = "http://www.walottery.com/RSS.xml"
PURCHASES=10

winningNumbers = [14, 18, 19, 28, 36]
winningNumbers = [4, 5, 29, 37, 38]
winningNumbers = [01,04,16,22,28]

class Hit5:
  def __init__(self):
    self.frequencypage = FREQUENCYPAGE
    self.winningnumberspage = WINNINGNUMBERSPAGE

  def getFrequencies(self):
    webpage = urllib2.urlopen(self.frequencypage)
    response = webpage.read()

    found = False
    text_to_parse = []
    for line in response.split("\n"):
      if line.find("<!-- RIGHT TABLE -->") > -1:
        found = True
        #print "Found <!-- RIGHT TABLE -->"
   
      if found:
        text_to_parse.append(line) 

    soup = BeautifulSoup(''.join(text_to_parse))

    table = soup.find('table')
    rows = table.findAll('tr')

    frequencies = []
    for tr in rows:
      cols = tr.findAll('td')
      items = []
      for td in cols:
        try:
          cell = int(td.find(text=True))
          items.append(cell)
        except ValueError, e:
          continue
      if len(items) != 0:
        frequencies.append((items[0], items[1]))
      #print frequencies

    #for ball in frequencies:
    #   print "Ball", ball[0], "has frequency of", ball[1]

    return frequencies

  def createBallPool(self):
    ballcollection = []

    for ball, frequency in self.getFrequencies():
      if frequency > 78 and frequency < 95:
        frequency *= 1.3
        frequency = int(frequency)
      for i in range(0, frequency):
        ballcollection.append(ball)
    return ballcollection

  def getLastWinningNumbers(self,game="Hit5"):
    import feedparser
    d = feedparser.parse(self.winningnumberspage)
    for feed in d["entries"]:
      print "\n"
      print feed['title']
      if feed['title'].find(game) > -1:
        print self.parseWinningNumbersFromFeed(feed['summary'])
    return

  def parseWinningNumbersFromFeed(self,feedSummary):
    pre, numbers = feedSummary.split(":")
    numbers, post = numbers.split(".")
    winningNumbers =  numbers.split(" - ")
    for i in range(0, len(winningNumbers)):
      winningNumbers[i] = int(winningNumbers[i])
    return winningNumbers


hit5 = Hit5()
hit5.getLastWinningNumbers()

winningmatches = [0,0,0,0,0]

for i in range(0,PURCHASES):
  myNumbers = []
  try: 
    collection = hit5.createBallPool()
    while len(myNumbers) < 5:
      index = random.randint(0,len(collection)-1)
      pick = collection[index]
      if pick not in myNumbers:
        myNumbers.append(pick)
  except IndexError, e:
    print index, "out of", len(collection)
   
  myNumbers.sort()
  print myNumbers
  matches = len( list(set(myNumbers) & set(winningNumbers)) ) 

  if matches > 1:
    #print "Found", matches, "matches in ticket:",  myNumbers
    winningmatches[matches-1] += 1
    
  if myNumbers == winningNumbers:
    print "Found the winning ticket in", i, "tries"
    break

print winningmatches
odds = float(sum(winningmatches)) / i
print odds
#print myNumbers
